//
//  Image.swift
//  CooperSwift
//
//  Created by Mac on 2020/1/8.
//  Copyright © 2020 CooperSwift. All rights reserved.
//

import Foundation
import UIKit

public extension UIImage {
    
    
    //init with color and size
    convenience init(color: UIColor, size: CGSize) {
       UIGraphicsBeginImageContextWithOptions(size, false, 1)
       color.setFill()
       UIRectFill(CGRect(x: 0, y: 0, width: size.width, height: size.height))
       guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
           self.init()
           return
       }
       UIGraphicsEndImageContext()
       guard let aCgImage = image.cgImage else {
           self.init()
           return
       }
       self.init(cgImage: aCgImage)
   }
   
   // simplified contentsOfFile: method
    convenience init(fileNamed: String) {
       let path = UIImage.createLocalUrl(forImageNamed: fileNamed)?.path
       self.init(contentsOfFile: path!)!
   }
   
   static func createLocalUrl(forImageNamed name: String) -> URL? {
       
       let fileManager = FileManager.default
       let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
       if name.contains(".jpg") {
           return cacheDirectory.appendingPathComponent(name)
       }
       let scale = UIScreen.main.scale
       var scaleName = ""
       switch scale {
       case 2:
           scaleName = name + "@2x.png"
       case 3:
           scaleName = name + "@3x.png"
       default:
           scaleName = name + ".png"
       }
       let url = cacheDirectory.appendingPathComponent("\(scaleName)")
       
       guard fileManager.fileExists(atPath: url.path) else {
           guard
               let image = UIImage(named: name),
            let data = image.pngData()
               else { return nil }
           
           fileManager.createFile(atPath: url.path, contents: data, attributes: nil)
           return url
       }
       
       return url
   }
    
    /// 圆角图片
    func withRoundedCorners(radius: CGFloat? = nil) -> UIImage? {
       let maxRadius = min(size.width, size.height) / 2
       let cornerRadius: CGFloat
       if let radius = radius, radius > 0 && radius <= maxRadius {
           cornerRadius = radius
       } else {
           cornerRadius = maxRadius
       }
       
       UIGraphicsBeginImageContextWithOptions(size, false, scale)
       
       let rect = CGRect(origin: .zero, size: size)
       UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
       draw(in: rect)
       
       let image = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()
       return image
   }
    
    /// 图片缩放
    func scaled(toHeight: CGFloat, opaque: Bool = false, with orientation: UIImage.Orientation? = nil) -> UIImage? {
       let scale = toHeight / size.height
       let newWidth = size.width * scale
       UIGraphicsBeginImageContextWithOptions(CGSize(width: newWidth, height: toHeight), opaque, scale)
       draw(in: CGRect(x: 0, y: 0, width: newWidth, height: toHeight))
       let newImage = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()
       return newImage
   }
   
    func scaled(toWidth: CGFloat, opaque: Bool = false, with orientation: UIImage.Orientation? = nil) -> UIImage? {
       let scale = toWidth / size.width
       let newHeight = size.height * scale
       UIGraphicsBeginImageContextWithOptions(CGSize(width: toWidth, height: newHeight), opaque, scale)
       draw(in: CGRect(x: 0, y: 0, width: toWidth, height: newHeight))
       let newImage = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()
       return newImage
   }
    
    /// 根据radius,corners,borderWidth,borderColor,borderLineJoin生成新的图片
    func image(radius: CGFloat, borderWidth: CGFloat, borderColor: UIColor) -> UIImage? {
        return image(radius: radius, corners: UIRectCorner.allCorners, borderWidth: borderWidth, borderColor: borderColor, borderLineJoin: .miter)
    }

    func image(radius: CGFloat, corners: UIRectCorner, borderWidth: CGFloat, borderColor: UIColor, borderLineJoin: CGLineJoin) -> UIImage? {
          /*
           /* Line join styles. */
           
           public enum CGLineJoin : Int32 {
           
           case miter
           
           case round
           
           case bevel
           }
           */
          
          UIGraphicsBeginImageContextWithOptions(size, false, scale)
          let context = UIGraphicsGetCurrentContext()
          let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
          context?.scaleBy(x: 1, y: -1)
          context?.translateBy(x: 0, y: -rect.size.height)
          
          let minSize = min(size.width, size.height)
          if borderWidth < minSize / 2 {
              let path = UIBezierPath.init(roundedRect: rect.insetBy(dx: borderWidth, dy: borderWidth), byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: borderWidth))
              path.close()
              
              context?.saveGState()
              path.addClip()
              context?.draw(cgImage!, in: rect)
              context?.restoreGState()
          }
          
          if borderWidth > 0 && borderWidth < minSize / 2 {
              let strokeInset = (floor(borderWidth*scale)+0.5) / scale
              let strokeRect = rect.insetBy(dx: strokeInset, dy: strokeInset)
              let strokeRadius = radius > scale / 2 ? radius-scale/2 : 0
              
              let path = UIBezierPath.init(roundedRect: strokeRect, byRoundingCorners: corners, cornerRadii: CGSize(width: strokeRadius, height: borderWidth))
              path.close()
              
              path.lineWidth = borderWidth
              path.lineJoinStyle = borderLineJoin
              borderColor.setStroke()
              path.stroke()
          }
          
          let image = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()
          
          return image
    }
    /// 根据color和size生成新的图片
    func image(color: UIColor, size: CGSize) -> UIImage? {
       if size.width <= 0 || size.height <= 0 {
           return nil
       }
       
       let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
       UIGraphicsBeginImageContextWithOptions(size, false, 0)
       let context = UIGraphicsGetCurrentContext()
       context?.setFillColor(color.cgColor)
       context?.fill(rect)
       
       let image = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()
       
       return image
   }
    
    /// Mask images with UIColor.
    /// - Parameter color: 填充颜色
    func maskingwithColor(_ color: UIColor) -> UIImage? {
        
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        let context = UIGraphicsGetCurrentContext()!
        
        color.setFill()
        
        context.translateBy(x: 0, y: self.size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        
        let rect = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height)
        context.draw(self.cgImage!, in: rect)
        
        context.setBlendMode(CGBlendMode.sourceIn)
        context.addRect(rect)
        context.drawPath(using: CGPathDrawingMode.fill)
        
        let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return coloredImage
    }
    
}
